<?php

namespace app\service;

/**
 * Class Swoolecli
 */
class Swoolecli
{
    private $client;

    public function __construct()
    {
        $this->client = new \swoole_client(SWOOLE_SOCK_TCP);
    }

    public function connect($port = 9502)
    {
        if (!$this->client->connect("127.0.0.1", $port, -1)) {
            throw new \Exception(sprintf('Swoole Error: %s', $this->client->errCode));
        }
    }

    public function send($data)
    {
        if (!$this->client->isConnected()) {
            throw new \Exception('Swoole Server does not connected.');
        }
        $data = !is_string($data) ? json_encode($data) : $data;
        return $this->client->send($data . "\r\n");
    }

    public function close()
    {
        $this->client->close();
    }
}  